package com.zhugang.week13.tree;

import java.util.*;

/**
 * @program algorithms
 * @description: levelOrder
 * @author: chanzhugang
 * @create: 2022/12/16 01:50
 */
public class LevelOrder {

    /**
     * 剑指offer 32-I 从上到下打印二叉树
     * https://leetcode.cn/problems/cong-shang-dao-xia-da-yin-er-cha-shu-lcof/
     *
     * @param root
     * @return
     */
    public int[] levelOrder(TreeNode root) {
        // 层序遍历：队列
        List<Integer> list = new ArrayList<>();
        LinkedList<TreeNode> queue = new LinkedList<>();
        queue.add(root);
        while (!queue.isEmpty()) {
            TreeNode node = queue.pop();
            list.add(node.val);
            if (node.left != null) {
                queue.add(node.left);
            }
            if (node.right != null) {
                queue.add(node.right);
            }
        }
        return list.stream().mapToInt(i -> i).toArray();
    }


    public class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        TreeNode(int x) {
            val = x;
        }
    }
}